package br.com.infocruz.seam.crm.ejb.facade;

import java.util.Date;

import javax.interceptor.InvocationContext;

import org.apache.log4j.Logger;
import org.jboss.seam.Component;
import org.jboss.seam.security.Identity;

//@Interceptor(stateless = true, around = { BijectionInterceptor.class, ConversationInterceptor.class }, within = RemoveInterceptor.class, type=InterceptorType.ANY)
public class AuditTrailInterceptor {
	private static final long serialVersionUID = 1L;
	
	private static Logger log = Logger.getLogger(AuditTrailInterceptor.class);
	
	public AuditTrailInterceptor() {
	}
	
//	@AroundInvoke
	@javax.interceptor.AroundInvoke
	public Object aroundInvoke(final InvocationContext invocation) throws Exception {
		final String methodName = invocation.getMethod().getName();
		final String className = invocation.getTarget().toString();
		log.debug("calling: " + className + "::" + methodName);
		final long start = System.currentTimeMillis();
		final Object result = invocation.proceed();
		final long end = System.currentTimeMillis();
		final double time = (end - start) / 1000.0;
		log.debug("call took: " + time);

//		Events.instance().raiseEvent("br.com.infocruz.seam.crm.createAudit", className, methodName, new Date(start), new Date(end), user);
		AuditTrailFacade auditTrailFacade = getAuditFacade();
		auditTrailFacade.createAudit(className, methodName, new Date(start), new Date(end), getUsername());
		
		return result;
	}

	private AuditTrailFacade getAuditFacade() {
		return (AuditTrailFacade)Component.getInstance(AuditTrailFacadeBean.class);
	}
	
	private String getUsername() {
		Identity identity = (Identity)Component.getInstance(Identity.class);
		if(identity == null){
			return null;
		}
		return identity.getPrincipal() != null ? identity.getPrincipal().getName() : null;
	}
	
}
